<template>
    <view class="waimaiitem item">
        <view class="store" @click="toLink('store')">
            <view class="storeInfo">
                <view class="store_logo">
                    <image :src="objInfo.shop_logo || (globalData.imgStaticPath + '/shop.png')" @error="objInfo.shop_logo = (globalData.imgStaticPath + '/shop.png'); " mode="aspectFill" ></image>
                </view>
                <view class="store_title">
                    <view class="h3">{{objInfo.shopname}}</view>
                    <view class="p order_time">{{timeTrans(objInfo.pubdate)}}</view>
                </view>
            </view>
            <view class="orderState">
                <view class="stateText">{{getState(objInfo)}}</view>
                <view class="cancel_info" v-if="objInfo.state == '6'">{{ objInfo.failed.includes('半小时内未支付，系统自动取消') ? '订单超时未支付' : objInfo.failed }}</view>
            </view>
        </view>
        <view class="order-content"  @click="toLink('order')">
            <!-- 店铺已接单 需显示地图  餐品只显示文字 -->
            <template v-if="objInfo.state == 3 || objInfo.state == 4 || objInfo.state == 5">
                <view class="flexbox showText" v-if="objInfo.state == 3 || objInfo.state == 4 || objInfo.state == 5">
                    <view class="food"><view class="food_text"> {{ objInfo.food }} </view>{{ objInfo.foodList.length > 1 ? `共${objInfo.foodCount}件商品` : ``}}</view>
                    <view class="price">
                        <view>
                            <text class="symbol">{{globalData.appConfig && globalData.appConfig.currency && globalData.appConfig.currency.symbol || '￥'}}</text>
                            <text class="b">{{ objInfo.amount.split('.')[0] }}</text>
                            <text class="smNumber" v-if=" (parseFloat(objInfo.amount)).toString().includes('.')">.{{  (parseFloat(objInfo.amount)).toString().split('.')[1] }}</text>
                        </view>
                        
                        <!-- <view class="p_text">{{globalData.appConfig&& globalData.appConfig.currency && globalData.appConfig.currency.symbol || '￥'}}<view class="b">{{ objInfo.amount }}</view></view> -->
                    </view>
                </view>
                <view class="mapShow" ref="mapCon" :id="`map_${objInfo.id}`" v-if="showMap">
                    <map style="width: 100%; height: 100%;" :id="`${objInfo.id}`" :scale="14" :customCallout="true" v-if="platForm != 'web'" :latitude="lnglat['lat']" :longitude="lnglat['lng']" :markers="covers" >
				        </map>
                </view>
            </template>
            <view class="flexbox showImg" v-else>
                <view class="food">
                    <view class="fImg loadingImg" v-for="item in (objInfo.foodList.slice(0, 3))" :key="item">
                        <image
                            :src="item.pic || defaultPro"
                            mode="aspectFill"
                            @error="item.pic = defaultPro"
                        ></image>
                    </view>
                    <view class="fTitle" v-if="objInfo.foodList.length == 1 && objInfo.foodList[0].title">{{ objInfo.foodList[0].title.replace(/\//g,'，').replace(/#/g,'，') }}</view>
                </view>
                <view class="price">
                    <view>
                        <text class="symbol">{{globalData.appConfig && globalData.appConfig.currency && globalData.appConfig.currency.symbol || '￥'}}</text>
                        <text class="b">{{ objInfo.amount.split('.')[0] }}</text>
                        <text class="smNumber" v-if=" (parseFloat(objInfo.amount)).toString().includes('.')">.{{  (parseFloat(objInfo.amount)).toString().split('.')[1] }}</text>
                    </view>
                    <view class="fcount">共{{ objInfo.foodCount }}件</view>
                </view>
            </view>
        </view>
        <view class="order_bottom" v-if="objInfo.reservesongdate || !['3','4'].includes(objInfo.state)">
            <view class="preOrder_info">
                <!-- v-if="objInfo.reservesongdate" -->
                <view class="info_text" v-if="objInfo.reservesongdate">预定订单,预订时间{{ timeTrans(objInfo.reservesongdate,1) }}</view>
            </view>
            <view class="order_btns" v-if="!['3','4'].includes(objInfo.state)">
                <template v-if="objInfo.state == '0'">
                    <view class="btn" @click="cancleOrder">取消订单</view>
                    <view class="btn bgBtn" @click="payOrder">去付款</view>
                </template>
                <template v-else-if="objInfo.state == '1' || objInfo.state == '6' || objInfo.state == '5' || objInfo.state == '7'  ">
                    <view class="btn" v-if="objInfo.state == '6'"  @click="toLink('store')">重新下单</view>
                    <view class="btn" @click="toLink('order')" v-else>查看详情</view>
                    <view class="btn borderBtn" v-if="objInfo.state == '1'  && objInfo.iscomment != 1" @click="toLink('comment')">评价</view>
                </template>
                <template v-else-if="objInfo.state == '2'">
                    <view class="btn" @click="cancleOrder">取消订单</view>
                </template>
            </view>
        </view>
    </view>

</template>

<script>
    const app = getApp();
    var map;
    export default {
        emits:['cancelorder','payorder'],
        props:{
            objInfo:{
                type:Object,
                default:{
                    
                }
            },
            ind:{
                type:Number,
                default:0
            }
        },
        computed:{
            // 获取状态文字
            getState(){
                return function(order){
                    const that = this;
                    let stateText = '';
                    let state = order.state
                    switch(state){
                        case  '0': 
                            stateText = '待付款'
                            break;
                        case  '1': 
                            if(order.iscomment){
                                stateText = '已完成'
                            }else{
                                stateText = '订单已送达'    
                            }
                            
                            break;
                        case  '2': 
                            stateText = '待确认'
                            break;
                        case  '3': 
                            if(order.selftime == 0){
                                stateText = '待配送'
                            }else{
                                stateText = '等待取餐'
                            }
                            break;
                        case  '4': 
                            stateText = '商家已接单'
                            break;
                        case  '5': 
                            stateText = '配送中'
                            break;
                        case  '6': 
                            stateText = '已取消'
                            break;
                        case  '7': 
                            stateText = '订单关闭'
                            break;
                    }

                    return stateText
                }
            },

            // 时间戳转换
            timeTrans(){
                return function(timestr,type = ''){

                    const dateFormatter = app.dateFormatter(timestr);
                    const year = dateFormatter.year;
                    const month = dateFormatter.month;
                    const day = dateFormatter.day;
                    const hour = dateFormatter.hour;
                    const minute = dateFormatter.minute;
                    const second = dateFormatter.second;
                    
                    let today_dateFormatter = app.dateFormatter(parseInt(new Date().valueOf() / 1000));
                    const today_year = today_dateFormatter.year;
                    const today_month = today_dateFormatter.month;
                    let showStr = '';
                    if(year == today_year){
                        showStr = month + '/' + day + ' ' + hour + ':' + minute ;
                    }else{
                        showStr = year + '/' + month + '/' + day + ' ' + hour + ':' + minute ;

                    }
                    if(type == 1){
                        if (new Date(timestr).toDateString() === new Date().toDateString()) {
                            showStr =  '今天 ' + hour + ':' + minute ;
                        } else if (new Date(timestr) < new Date()) {
                            showStr =  month + '/' + day + ' ' + hour + ':' + minute ;
                        }
                        
                    }
                    return showStr
                }
            },

            
        },
        data(){
            return {
                platForm:app.globalData.platForm,
                globalData:app.globalData,
                defaultPro:app.globalData.masterDomain + '/static/images/good_default.png',
                covers:[],
                showMap:false,
                lnglat:''
            }
        },
        mounted(){
            this.checkMapShow()
            
        },
        methods:{
            // 是否显示地图
            checkMapShow(){
                const that = this;
                let info = that.objInfo;
                let showMap = false;
                let lnglat = '',content = ''
                if(info.state && ['3','4','5'].includes(info.state)){
                    switch(info.state){
                        case '3':
                            showMap = Boolean(info.shop_coordX && info.shop_coordY) || Boolean(info.peisongpath_lng && info.peisongpath_lat)
                            
                            if(Boolean(info.peisongpath_lng && info.peisongpath_lat)){
                                lnglat = {
                                    'lng':info.peisongpath_lng,
                                    'lat':info.peisongpath_lat
                                }
                                content = '等待骑手到店'
                            }else if(Boolean(info.shop_coordX && info.shop_coordY)){
                                lnglat = {
                                    'lng':info.shop_coordY,
                                    'lat':info.shop_coordX
                                }
                                content = '商家正在配货'
                            }
                            break;
                        case '4':
                            showMap = Boolean(info.shop_coordX && info.shop_coordY)
                            if(Boolean(info.shop_coordX && info.shop_coordY)){
                                lnglat = {
                                    'lng':info.shop_coordY,
                                    'lat':info.shop_coordX
                                }
                                content = '商家已接单'
                            }
                            break;
                        case '5':
                            showMap = Boolean(info.peisongpath_lng && info.peisongpath_lat)
                            if(Boolean(info.peisongpath_lng && info.peisongpath_lat)){
                                lnglat = {
                                    'lng':info.peisongpath_lng,
                                    'lat':info.peisongpath_lat
                                }
                            }
                            content = '骑手正在配送'
                            break;
                    }
                }
                that.showMap = showMap;
                that.lnglat = lnglat;
                if(lnglat && that.platForm == 'web'){
                    that.$nextTick(() => {
                        that.drawMap()
                    })
                }
                that.covers = [{
                    id:new Date().valueOf(),
                    latitude: lnglat.lat,
				    longitude: lnglat.lng,
                    iconPath:'',
                    width:0,
                    height:0,
                    callout:{
                        content:content,
                        color:'#000',
                        fontSize:14,
                        borderRadius:4,
                        bgColor:'#fff',
                        padding:8,
                        display:'ALWAYS'
                    }
                }]
            },

            // 绘制地图
            drawMap(){
                const that = this;
                if(!that.lnglat) return false;
                let lnglat = [that.lnglat.lng,that.lnglat.lat]
                if(that.platForm == 'web'){
                    if(site_map == 'baidu'){
                        that.draw_baidu(lnglat)
                    }else if(site_map == 'amap'){
                        // console.log('绘制1')
                        that.draw_aMap(lnglat)
                    }else if(site_map == 'tmap'){
                        that.draw_tmap(lnglat)
                    }else if(site_map == 'google'){
                        that.draw_google(lnglat);
                    }
                }
            },

            // 百度地图
            draw_baidu(lnglat){
                const that = this;
                const lng = lnglat[0];
                const lat = lnglat[1];
                // eslint-disable-next-line no-undef
                map = new BMap.Map(`map_${that.objInfo.id}`);          // 创建地图实例 
                var label = new BMap.Label('<div class="map_label" style="width: 0; height: 0; background-color: none; position: relative;"><div class="map_labCon" style="position: absolute; left: 50%; top: 50%; transform: translate(-50%,-40px); font-size:14px; border-radius:4px; background:#fff; padding:10px 14px; filter: drop-shadow(0px 4px 15px rgba(110,110,110,0.24));">'+ that.covers[0].callout.content +'<div class="map_arr" style="width:8px; height:8px; background:#fff; border-radius:2px; position:absolute; left:0; right:0; margin:auto; bottom:-4px; transform:rotate(45deg);"></div></div>',{
                    position: that.lnglat,
                    offset: new BMap.Size(0, 0)
                })
                map.addOverlay(label);
                // eslint-disable-next-line no-undef
                const point = new BMap.Point(lng, lat);  // 创建点坐标 
                map.centerAndZoom(point, 15); 
            },

            // 高德地图
            draw_aMap(lnglat){
                const that = this;
                let lng = +(lnglat[0] ? lnglat[0] : 120.738572);
                let lat = +(lnglat[1] ? lnglat[1] : 31.331029);
                map = new AMap.Map(`map_${that.objInfo.id}`, {
                    viewMode: '2D', //默认使用 2D 模式
                    zoom: 16, //地图级别
                    center: [lng, lat], //地图中心点
                });
                var label = new AMap.Marker({
                    position: [lng,lat],
                    content: '<div class="map_label" style="width: 0; height: 0; background-color: none; position: relative;"><div class="map_labCon" style="position: absolute; left: 50%; top: 50%; transform: translate(-50%,-40px); font-size:14px; border-radius:4px; background:#fff; white-space:nowrap; padding:10px 14px; filter:drop-shadow(0px 4px 15px rgba(110,110,110,0.24));">'+ that.covers[0].callout.content +'<div class="map_arr" style="width:8px; height:8px; background:#fff; border-radius:2px; position:absolute; left:0; right:0; margin:auto; bottom:-4px; transform:rotate(45deg);"></div></div>',
                    offset: new AMap.Pixel(0, 0),
                    map: map,
                });

            },

            // 天地图
            draw_tmap(lnglat){
                const that = this;
                map = new T.Map(`map_${that.objInfo.id}`);
                let lng = +(lnglat[0] ? lnglat[0] : 120.738572);
                let lat = +(lnglat[1] ? lnglat[1] : 31.331029);
                let center = new T.LngLat(lng, lat)
                var label = new T.Label({
                    text: '<div class="map_label" style="width: 0; height: 0; background-color: none; position: relative;"><div class="map_labCon" style="position: absolute; left: 50%; top: 50%; transform: translate(-50%,-40px); font-size:14px; border-radius:4px; background:#fff; white-space:nowrap; padding:4px 14px; filter:drop-shadow(0px 4px 15px rgba(110,110,110,0.24));">'+ that.covers[0].callout.content +'<div class="map_arr" style="width:8px; height:8px; background:#fff; border-radius:2px; position:absolute; left:0; right:0; margin:auto; bottom:-4px; transform:rotate(45deg);"></div></div>',
                    position: center,
                    offset: new T.Point(-18, 9)
                });
                //创建地图文本对象
                map.addOverLay(label);
                map.centerAndZoom(center, 14);
            },

            // 谷歌地图 没测试
            async draw_google(lnglat){
                const that = this;
                let lng = +(lnglat[0] ? lnglat[0] : 120.738572);
                let lat = +(lnglat[1] ? lnglat[1] : 31.331029);
                const { Map } = await google.maps.importLibrary("maps");
                map = new Map(document.getElementById(`map_${that.objInfo.id}`), {
                    center: { lat: lat, lng: lng },
                    zoom: 8,
                });
            },


            /**
             * 跳转链接
             * @param {string} type 跳转的链接类型  
             *  order => 订单详情   store => 店铺详情
             * */ 
            toLink(type){
                let url = ''
                if(type == 'order'){
                    url = `${app.globalData.appConfig.cfg_user_index}/orderdetail-waimai-${this.objInfo.id}.html`
                }else if(type == 'store'){
                    url = `${app.globalData.masterDomain}/waimai/shop?id=${this.objInfo.sid}`
                }else if(type == 'comment'){
                    url = `${app.globalData.appConfig.cfg_user_index}/write-comment-waimai-${this.objInfo.id}.html`
                }
                app.linkTo(url,false,false)
            },

            // 取消订单
            cancleOrder(){
                uni.$emit('cancelorder',{objInfo:this.objInfo,ind:this.ind})
            },

            // 继续支付
            payOrder(){
                uni.$emit('payorder',{objInfo:this.objInfo,ind:this.ind})
            },
        },
    }
</script>

<style scoped>
    @import './orderlist_waimai.css'
</style>